<template>
  <div>
    <!-- 面包屑组件 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片组件 -->
    <el-card class="box-card">
      <!-- 分栏布局  栅格系统 == Loyout组件 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索与添加区 -->
          <el-input
            placeholder="请输入内容"
            v-model="paramsInfo.query"
            clearable
            @clear="getUser"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUser"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template v-slot="scoped">
            <el-switch
              v-model="scoped.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="UserInfoStatus(scoped.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scoped">
            <!-- 编辑页面 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="seteditFn(scoped.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteuserFn(scoped.row.id)"
            ></el-button>
            <!-- 分配权限 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分类管理"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scoped.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[1, 2, 5]"
        :page-size="paramsInfo.pagesize"
        layout="total,prev, pager, next, jumper,sizes"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户区 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addialogVisible"
      width="50%"
      @close="addresetFn"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户 -->
    <el-dialog
      title="修改用户"
      :visible.sync="showEdit"
      width="50%"
      @close="editDialong"
    >
      <!-- 主体内容 -->
      <el-form
        :model="editForm"
        :rules="addrules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEdit = false">取 消</el-button>
        <el-button type="primary" @click="sureEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRoledialogVisible"
      width="50%"
      @close="closeRoleFn"
    >
      <div>
        <p>当前的用户是：{{ userInfo.username }}</p>
        <p>当前的角色是：{{ userInfo.role_name }}</p>
        <p>
          分配角色：
          <el-select v-model="selectRoleID" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRolseFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证手机号
    // let checkMobile = (rule, value, callback) =>{
    //    let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

    //    if(!reg.test(value)) return callback(new Error('请输入合法的手机号'))
    //    callback()
    // }
    return {
      // 查询参数
      paramsInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      // 获取用户列表
      userList: [],
      // 总条数
      total: 0,
      // 添加用户区显示与隐藏
      addialogVisible: false,
      // 添加表单对象
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加表单定义规则
      addrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到6个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 3 到16个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          // { validator: checkMobile, trigger: 'blur' }
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
            message: "请输入合法的手机号",
            trigger: "blur",
          },
        ],
      },
      // 编辑用户区显示与隐藏
      showEdit: false,
      // 编辑表单对象
      editForm: {
        email: "",
        mobile: "",
      },
      // 展示分配权限的对象框
      setRoledialogVisible: false,
      userInfo: {},
      // b保存角色列表
      roleList: [],
      // 保存角色ID 与 value绑定的id一致
      selectRoleID: "",
    };
  },
  created() {
    this.getUser();
  },
  methods: {
    // 获取用户列表
    async getUser() {
      const { data: res } = await this.$axios.get("users", {
        params: this.paramsInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败！");
      // console.log(res.data);
      this.total = res.data.total;
      this.userList = res.data.users;
      //   console.log( this.userList);
    },
    // 显示条数
    handleSizeChange(newhand) {
      console.log("newhand", newhand);
      this.paramsInfo.pagesize = newhand;
      this.getUser();
    },
    // 页码
    handleCurrentChange(page) {
      console.log("page", page);
      this.paramsInfo.pagenum = page;
      this.getUser();
    },
    // 监听Switch开关
    async UserInfoStatus(userInfo) {
      const { data: res } = await this.$axios.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新用户状态失败！");
      }
      this.$message.success("更新用户信息成功");
    },
    // 添加用户表单重置
    addresetFn() {
      this.$refs.addFormRef.resetFields();
    },
    // 表单预验证
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("验证失败");
        const { data: res } = await this.$axios.post("users", this.addForm);
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功");
        this.getUser();
        this.addialogVisible = false;
      });
      //  this.addialogVisible = false
    },
    // 根据id查询数据
    async seteditFn(id) {
      // console.log(id);
      this.editid = id;
      const { data: res } = await this.$axios.get("users/" + id);
      if (res.meta.status !== 200)
        return this.$message.error("查询用户信息失败");
      this.editForm = res.data;
      this.showEdit = true;
    },
    // 根据id编辑用户信息 进行表单预验证 == 并提交
    sureEdit() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("不合法，请重新输入");
        const { data: res } = await this.$axios.put(
          `users/${this.editForm.id}`,
          {
            mobile: this.editForm.mobile,
            email: this.editForm.email,
          }
        );
        // console.log(res);
        if (res.meta.status !== 200)
          return this.$message.error("编辑用户信息失败");
        // console.log(res);
        this.getUser();
        this.showEdit = false;
        // console.log(this.editForm);
        this.$message.success("编辑用户信息成功");
        // this.editForm = '',
        this.editid = "";
      });
    },
    // 修改用户表单重置
    editDialong() {
      this.$refs.editFormRef.resetFields();
    },
    // 根据id删除操作
    async deleteuserFn(id) {
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res !== "confirm") return this.$message.info("您取消的删除操作");
      //
      // console.log(id);
      const { data: res1 } = await this.$axios.delete("users/" + id);
      // console.log(res1);
      if (res1.meta.status !== 200) return this.$message.error("删除用户失败");
      this.$message.success("删除用户成功");
      if (this.total % this.paramsInfo.pagesize === 1) {
        this.paramsInfo.pagenum--;
      }
      this.getUser();
    },
    // 展示分配权限的对话框
    async setRole(role) {
      this.userInfo = role;
      console.log(this.userInfo);
      const { data: res } = await this.$axios.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.roleList = res.data;
      // console.log(this.roleList);
      this.setRoledialogVisible = true;
    },
    // 确定修改对话框角色分配
    async saveRolseFn() {
      if (!this.selectRoleID) return this.$message.error("请选择分配的角色");
      const { data: res } = await this.$axios.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.selectRoleID }
      );
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("分配角色失败");
      this.$message.success("分配角色成功");
      this.getUser();
      this.setRoledialogVisible = false;
    },
    closeRoleFn() {
      (this.userInfo = ""), (this.selectRoleID = "");
    },
  },
};
</script>

<style lang="less" scoped>
// <!-- 用户列表区上边距 -->
.el-table {
  margin-top: 18px;
}
</style>